package com.iotechn.unimall.admin.api.lease;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.LeaseDO;
import com.iotechn.unimall.data.domain.LeaseDetailsDO;
import com.iotechn.unimall.data.domain.LeaseSeedDO;
import com.iotechn.unimall.data.mapper.LeaseDetailsMapper;
import com.iotechn.unimall.data.mapper.LeaseMapper;
import com.iotechn.unimall.data.mapper.LeaseSeedMapper;
import com.iotechn.unimall.data.model.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class AdminLeaseServiceImpl implements AdminLeaseService {

    @Autowired
    private LeaseMapper leaseMapper;
    @Autowired
    private LeaseDetailsMapper detailsMapper;
    @Autowired
    private LeaseSeedMapper leaseSeedMapper;

    @Override
    public Page<LeaseDO> list(Integer page, Integer limit, String title, String categoryId, Long adminId) throws ServiceException {
        List<LeaseDO> LeaseDO = leaseMapper.selectListByBack(title, categoryId, (page - 1) * limit, limit);
        Long count = leaseMapper.countOrder(title, categoryId);
        return new Page<LeaseDO>(LeaseDO, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LeaseDO create(LeaseDO leaseDO, Long adminId) throws ServiceException {
        if (leaseMapper.insert(leaseDO) > 0) {
            Long id = leaseDO.getId();
            leaseDO.setId(id);
            String ids = leaseDO.getIds();
            if(ids != null){
                String[] ss = ids.split(",");
                for (String s : ss) {
                    LeaseSeedDO leaseSeedDO = new LeaseSeedDO();
                    leaseSeedDO.setLeaseId(id);
                    leaseSeedDO.setSeedId(Long.valueOf(s));
                    leaseSeedMapper.insert(leaseSeedDO);
                }
            }
            return leaseDO;
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(LeaseDO leaseDO, Long adminId) throws ServiceException {
        Long id = leaseDO.getId();
        if (id == null) return "fail";
        if (leaseMapper.updateById(leaseDO) > 0) {
            String ids = leaseDO.getIds();
            // 删除原始信息
            leaseSeedMapper.delete(new EntityWrapper<LeaseSeedDO>().eq("lease_id",id));
            if(ids != null){
                String[] ss = ids.split(",");
                for (String s : ss) {
                    LeaseSeedDO leaseSeedDO = new LeaseSeedDO();
                    leaseSeedDO.setLeaseId(id);
                    leaseSeedDO.setSeedId(Long.valueOf(s));
                    leaseSeedMapper.insert(leaseSeedDO);
                }
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        Integer count = detailsMapper.selectCount(new EntityWrapper<LeaseDetailsDO>().eq("lease_id", id));
        if(count > 0)
            throw new AdminServiceException(ExceptionDefinition.LEASE_CANNOT_DELETE);
        if (leaseMapper.deleteById(id) > 0) {
            // 删除旗下所有关联种子
            leaseSeedMapper.delete(new EntityWrapper<LeaseSeedDO>().eq("lease_id",id));
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    public LeaseDO detail(Long id, Long adminId) throws ServiceException {
        LeaseDO leaseDO = leaseMapper.selectById(id);
        List<Map<String, Object>> mapList =
                leaseSeedMapper.selectMaps(new EntityWrapper<LeaseSeedDO>().setSqlSelect(" GROUP_CONCAT(seed_id) AS ids ").eq("lease_id", id));
        if(!CollectionUtils.isEmpty(mapList) && mapList.get(0) != null){
            leaseDO.setIds(mapList.get(0).get("ids").toString());
        }
        return leaseDO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchDelete(String idsJson, Long adminId) throws ServiceException {
        List<Long> ids = JSONObject.parseArray(idsJson, Long.class);
        if (CollectionUtils.isEmpty(ids))
            throw new AdminServiceException(ExceptionDefinition.LEASE_NOT_EXIST);
        if (leaseMapper.delete(new EntityWrapper<LeaseDO>().in("id", ids)) <= 0)
            throw new AdminServiceException(ExceptionDefinition.LEASE_NOT_EXIST);
        detailsMapper.delete(new EntityWrapper<LeaseDetailsDO>().in("lease_id", ids));
        return "ok";
    }

    @Override
    public List<LeaseDO> select(Long adminId) {
        Wrapper<LeaseDO> wrapper = new EntityWrapper<LeaseDO>()
                .setSqlSelect("id", "title").orderBy("id", false);
        return leaseMapper.selectList(wrapper);
    }
}
